package com.example.scoredemo.widgets

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.text.TextPaint
import android.text.TextUtils
import android.util.AttributeSet
import android.view.ViewGroup
import android.view.animation.*
import android.widget.TextView

@SuppressLint("AppCompatCustomView")
class MyView : TextView {
    private var first = true

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        viewTreeObserver.addOnPreDrawListener {
            initTextInfo()
            true
        }
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs, 0) {
        viewTreeObserver.addOnPreDrawListener {
            initTextInfo()
            true
        }
    }

    constructor(context: Context?) : super(context) {
        viewTreeObserver.addOnPreDrawListener {
            initTextInfo()
            true
        }
    }

    var mTextSize: Float = 0f
    var textLineHeight = 0f
    val mTop = 0
    var y = 0
    var mLines = 0
    var mBottom = 0
    var mRight = 0
    var mLeft = 0
    var lineDrawWords = 0
    lateinit var mTextCharArray: CharArray
    var singleWordWidth = 0f

    private var mLineSpacingExtra = 0f

    fun initTextInfo() {
        mTextSize = textSize
        textLineHeight = lineHeight.toFloat()
        mLeft = 0
        mRight = right
        y = top
        mLineSpacingExtra = lineSpacingExtra

        // 要画的宽度
        val drawTotalWidth = right - left
        val text = text.toString()
        if (!TextUtils.isEmpty(text) && first) {
            mTextCharArray = text.toCharArray()
            val mTextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
            mTextPaint.density = resources.displayMetrics.density
            mTextPaint.textSize = mTextSize
            // 一个单词的的宽度
            singleWordWidth = mTextPaint.measureText("一") + mLineSpacingExtra
            // 一行可以放多少个字符
            lineDrawWords = (drawTotalWidth / singleWordWidth).toInt()
            val length = mTextCharArray.size
            mLines = length / lineDrawWords
            if (length % lineDrawWords > 0) {
                mLines += 1
            }
            first = false
            val layoutParams: ViewGroup.MarginLayoutParams = layoutParams as ViewGroup.MarginLayoutParams
            val totalHeight = (mLines * textLineHeight + textLineHeight * 2 + paddingBottom + paddingTop + layoutParams.bottomMargin + layoutParams.topMargin).toInt()
            height = totalHeight
        }
    }

    override fun onDraw(canvas: Canvas) {
        bottom = getBottom()
        var drawTotalLine = mLines
        if (maxLine != 0 && drawTotalLine > maxLine) {
            drawTotalLine = maxLine
        }
        for (i in 0 until drawTotalLine) {
            try {
                val length = mTextCharArray.size
                var mLeft = left
                // 第i+1行开始的字符index
                var startIndex = i * 1 * lineDrawWords
                // 第i+1行结束的字符index
                var endTextIndex = startIndex + lineDrawWords
                if (endTextIndex > length) {
                    endTextIndex = length
                    y += textLineHeight.toInt()
                } else {
                    y += textLineHeight.toInt()
                }
                while (startIndex < endTextIndex) {
                    val c = mTextCharArray[startIndex]
                    canvas.drawText(c.toString(), mLeft.toFloat(), y.toFloat(), paint)
                    mLeft += singleWordWidth.toInt()
                    startIndex++
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    var maxLine = 0

    override fun setMaxLines(max: Int) {
        maxLine = max
    }

    fun setLineSpacingExtra(lineSpacingExtra: Int) {
        mLineSpacingExtra = lineSpacingExtra.toFloat()
    }

    /**
     * 判断是否为中文
     * @return
     */
    fun containChinese(string: String): Boolean {
        var flag = false
        for (i in 0 until string.length) {
            val c = string[i]
            if (c.toInt() in 0x4e00..0x9FA5) {
                flag = true
            }
        }
        return flag
    }


    fun ToDBC(input: String): String? {
        // 导致TextView异常换行的原因：安卓默认数字、字母不能为第一行以后每行的开头字符，因为数字、字母为半角字符
        // 所以我们只需要将半角字符转换为全角字符即可
        val c = input.toCharArray()
        for (i in c.indices) {
            if (c[i] == ' ') {
                c[i] = '\u3000'
            } else if (c[i] < '\u007f') {
                c[i] = (c[i] + 65248)
            }
        }
        return String(c)
    }

}